#!/usr/bin/env python3
"""
测试运行脚本
用于依次运行服务器端和客户端测试
"""

import os
import sys
import subprocess
import time

def run_server_tests():
    """运行服务器端测试"""
    print("开始运行服务器端测试...")
    print("=" * 50)
    
    server_tests = [
        "test_backend.py",
        "test_search.py", 
        "test_cors.py",
        "test_deployment.py"
    ]
    
    for test_file in server_tests:
        test_path = os.path.join("server", test_file)
        print(f"\n运行 {test_file}...")
        
        try:
            # 运行Python测试文件
            result = subprocess.run([
                sys.executable, test_path
            ], capture_output=True, text=True, timeout=30)
            
            if result.returncode == 0:
                print(f"[PASS] {test_file} 测试通过")
                # 显示测试输出
                if result.stdout and result.stdout.strip():
                    print("   输出:", result.stdout.strip())
            else:
                print(f"[FAIL] {test_file} 测试失败")
                error_output = ""
                if result.stderr and result.stderr.strip():
                    error_output = result.stderr.strip()
                elif result.stdout and result.stdout.strip():
                    error_output = result.stdout.strip()
                print("   错误:", error_output if error_output else "无错误信息")
                return False
                
        except subprocess.TimeoutExpired:
            print(f"[TIMEOUT] {test_file} 测试超时")
            return False
        except Exception as e:
            print(f"[ERROR] {test_file} 执行错误: {e}")
            return False
    
    print("\n[PASS] 所有服务器端测试通过！")
    return True

def run_client_tests():
    """运行客户端测试"""
    print("\n开始运行客户端测试...")
    print("=" * 50)
    
    client_tests = [
        "test_all_features.js",
        "test_display_mode.js",
        "test_proxy.js"
    ]
    
    for test_file in client_tests:
        test_path = os.path.join("client", test_file)
        print(f"\n运行 {test_file}...")
        
        try:
            # 运行Node.js测试文件
            result = subprocess.run([
                "node", test_path
            ], capture_output=True, text=True, timeout=30)
            
            if result.returncode == 0:
                print(f"[PASS] {test_file} 测试通过")
                # 显示测试输出
                if result.stdout and result.stdout.strip():
                    print("   输出:", result.stdout.strip())
            else:
                print(f"[FAIL] {test_file} 测试失败")
                error_output = ""
                if result.stderr and result.stderr.strip():
                    error_output = result.stderr.strip()
                elif result.stdout and result.stdout.strip():
                    error_output = result.stdout.strip()
                print("   错误:", error_output if error_output else "无错误信息")
                return False
                
        except subprocess.TimeoutExpired:
            print(f"[TIMEOUT] {test_file} 测试超时")
            return False
        except FileNotFoundError:
            print(f"[SKIP] Node.js未安装，跳过 {test_file}")
            continue
        except Exception as e:
            print(f"[ERROR] {test_file} 执行错误: {e}")
            return False
    
    print("\n[PASS] 所有客户端测试通过！")
    return True

def check_requirements():
    """检查运行环境要求"""
    print("检查运行环境...")
    
    # 检查Python
    try:
        python_version = subprocess.run([
            sys.executable, "--version"
        ], capture_output=True, text=True)
        print(f"[OK] Python: {python_version.stdout.strip()}")
    except:
        print("[FAIL] Python未正确安装")
        return False
    
    # 检查Node.js（可选）
    try:
        node_version = subprocess.run([
            "node", "--version"
        ], capture_output=True, text=True)
        print(f"[OK] Node.js: {node_version.stdout.strip()}")
    except:
        print("[SKIP] Node.js未安装，将跳过JavaScript测试")
    
    return True

def main():
    """主函数"""
    print("Molecule Scope 测试套件")
    print("=" * 50)
    
    # 检查环境
    if not check_requirements():
        print("\n[FAIL] 环境检查失败，请安装必要的运行环境")
        return 1
    
    # 运行服务器测试
    server_success = run_server_tests()
    
    # 运行客户端测试
    client_success = run_client_tests()
    
    # 返回结果
    if server_success and client_success:
        print("\n[PASS] 所有测试通过！可以发布版本。")
        return 0
    else:
        print("\n[FAIL] 测试失败，请修复问题后再发布。")
        return 1

if __name__ == "__main__":
    sys.exit(main())